<?php
set_time_limit(0);

include_once('../lib/config.php');
include_once('../lib/function.php');

$redis = new Redis();
$redis->connect(REDIS_IP,"6379");  //php客户端设置的ip及端口
if(!$redis) die('redis connect fail');
$redis->auth(REDIS_PASS);
$redis->select(1);

$GLOBALS['config']['master']['db_database'] = 'mh_lnpan';
$GLOBALS['config']['slave']['db_database']  = 'mh_lnpan';

$limit = 100;
while($limit--) {
  $stop = $redis->get('LNPAN_QUEUE_STOP');
  if($stop) {
    sleep(3);
    break;
  }

  $url = $redis->lPop(KEY_QUEUE_TO_DOWN);
  if ($url) {
    $localDir = dirname(__FILE__).'/../../files';
    $cmd  = 'cd '.$localDir.';';
    $cmd .= 'wget --debug --limit-rate=1000k --continue --timeout=120 --tries=5 --no-clobber --force-directories --no-host-directories '.$url;
    $result = shell_exec($cmd);

    $parse = parse_url($url);
    $filepath = $localDir.$parse['path'];
    clearstatcache();
    $filesize = (int) filesize($filepath);
    if(!file_exists($filepath) || $filesize < 1000) {
      $redis->rPush(KEY_QUEUE_TO_DOWN, $url);
       if($filesize) {
          $ret = unlink($filepath);
	        var_dump($ret);
      }
	var_dump(file_exists($filepath), $filesize);
	sleep(1);

    } else {
      $redis->lPush(KEY_QUEUE_LOCAL_DOWN_SUCCESS, date('Y-m-d H:i:s').':http://dl.lnpan.com/files'.$parse['path']);
      $redis->rPush(KEY_QUEUE_TO_UPLOAD, $url);
    }

    echo2($url.' # '.$filepath);
  } else {
    echo2('lnpan_down queue empty');
	   sleep(10);
  }

  //break;
}
